package com.kun.ext;

import com.kun.annoations.FieldSensitive;
import com.kun.desensitized.handler.DesensitizedHandler;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.lang.Nullable;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kun.li
 */
public class DesensitizedInterceptor implements CustomInterceptor {


    private List<DesensitizedHandler> desensitizedHandler;

    public void setDesensitizedHandler(List<DesensitizedHandler> desensitizedHandler) {
        this.desensitizedHandler = desensitizedHandler;
    }


    @Override
    public Object doInvokeResult(Object result) throws Throwable {
        return desensitized(result);
    }

    public Object desensitized(Object result) throws Throwable {
        if (result instanceof List) {
            List<Object> resultList = (List<Object>) result;
            Map<String, String> map = new HashMap<>();
            for (Object resultObj : resultList) {
                Field[] declaredFields = resultObj.getClass().getDeclaredFields();
                for (Field field : declaredFields) {
                    FieldSensitive fieldSen = AnnotationUtils.findAnnotation(field, FieldSensitive.class);
                    if (fieldSen != null) {
                        map.put(field.getName(), field.getName());
                        field.setAccessible(true);
                        String oldFieldValue = String.valueOf(field.get(resultObj));
                        DesensitizedHandler handler = getDesensitizedHandler(fieldSen);
                        String desensitizedValue = handler.getDesensitizedValue(oldFieldValue);
                        field.set(resultObj, desensitizedValue);
                    }
                }
            }
        }

        return result;
    }

    @Nullable
    private DesensitizedHandler getDesensitizedHandler(FieldSensitive fieldSen) {
        for (DesensitizedHandler handler : desensitizedHandler) {
            if (handler.supportType(fieldSen.value())) {
                return handler;
            }
        }
        return null;
    }
}
